import json
import os
import re
import time

import requests


user_id = input('请输入用户id:')

headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
}
toutiao_base = open('toutiao_base.js').read()
with open('toutiao.js', 'w') as f:
    f.write(toutiao_base + f'\nconsole.info(window.TAC.sign("{user_id}0"));')
while True:
    as_cp = os.popen('node toutiao.js')
    s = as_cp.read()
    as_, cp_, signature = re.findall("as: '(.*?)', cp: '(.*?)' }\n(.*?)\n", s)[0]
    # # 这个cookie里面是有通行证的，每次访问都要带这个cookie
    resp_cookie = requests.get('https://www.toutiao.com', headers=headers).cookies
    # print(resp_cookie)
    i = 0
    while True:
        response = requests.get(
            f'https://www.toutiao.com/c/user/article/?page_type=1&user_id={user_id}&max_behot_time=0&count=20&_signature={signature}',
            headers=headers,cookies=resp_cookie)
        i += 1
        # print(response.url)
        data = json.loads(response.text)["data"]
        if data:
            print(data)
            break
    print(f"本次循环了{i}次")
    print("休眠2秒。。。")
    time.sleep(2)

